﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using VirtualHost.Models;
using VirtualHost.Services;

namespace VirtualHost.WinForm {
    public partial class FrmSiteEdit : WinFormBase {

        HostSiteEntity model = null;
        NginxConfigService nginxConfigService = null;
        public FrmSiteEdit(NginxConfigService nginxConfigService) {
            InitializeComponent();
            this.nginxConfigService = nginxConfigService;
        }

        public DialogResult Create() {
            model = new HostSiteEntity();


            return ShowDialog();
        }

        public DialogResult Modify(HostSiteEntity data) {
            model = data;
            txtName.Text = data.Name;
            txtDomain.Text = data.Domain;
            txtPort.Text = data.Port;
            chkHttps.Checked = data.IsHttps;
            txtPath.Text = data.Path;
            txtHome.Text = data.Home;
            txtCertificate.Text = data.Certificate;
            txtCertificateKey.Text = data.CertificateKey;
            return ShowDialog();
        }

        private void btnClose_Click(object sender, EventArgs e) {
            this.Close();
        }

        private void btnSave_Click(object sender, EventArgs e) {
            model.Name = txtName.Text;
            model.Domain = txtDomain.Text;
            if (int.TryParse(txtPort.Text, out int port)) {
                model.Port = txtPort.Text; // 注意：如果Port是整数类型，则需要解析  
            }
            model.IsHttps = chkHttps.Checked; // 注意：属性名可能应为IsHttps，而不是chkHtpps（假设的拼写错误）  
            model.Path = txtPath.Text;
            model.Home = txtHome.Text;
            model.Certificate = txtCertificate.Text;
            model.CertificateKey = txtCertificateKey.Text;
            if (String.IsNullOrEmpty(model.Id)) {
                this.model.Id = Guid.NewGuid().ToString("N").Substring(0x00, 8);
                this.Insert();
            } else {
                this.DbUpdate();
            }
        }

        private void Insert() {
            nginxConfigService.HostSites.Add(model);
            nginxConfigService.SaveConfigFile();
            DialogResult = DialogResult.OK;
        }

        private void DbUpdate() {

            nginxConfigService.SaveConfigFile();
            DialogResult = DialogResult.OK;
        }


    }
}
